<template>
    <div class="f-c-c h100vh login">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm" status-icon>
            <el-form-item prop="account">
                <template #label>
                    <div style="color:#fff">账号名</div>
                </template>
                <el-input placeholder="请输入账号" v-model="ruleForm.account" />
            </el-form-item>
            <el-form-item prop="password">
                <template #label>
                    <div style="color:#fff">密码</div>
                </template>
                <el-input placeholder="请输入密码" v-model="ruleForm.password" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm(ruleFormRef)">
                    登录
                </el-button>
            </el-form-item>
        </el-form>
    </div>
</template>
    
<script setup lang='ts'>
import { reactive, ref } from 'vue'
import type { FormInstance } from 'element-plus'
import { FormRules,ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
// 路由
const router=useRouter()
// 登录表单的TS要求格式
const ruleFormRef = ref<FormInstance>()
// 与登录的表单双向绑定
const ruleForm = reactive({
    account: '',
    password: '',
})
const loading = ref(false)

const rules = reactive<FormRules>({
    account: { required: true, message: "请输入账号名" },
    password: { required: true, message: "请输入密码" }
})

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log('submit!')
            loading.value=true
            fetch("http://jacklv.cn/users/login",{
                method:'post',
                body:JSON.stringify(ruleForm),
                headers:{
                    "Content-Type":"application/json"
                }
            }).then(response=>response.json())
            .then(res=>{
                console.log('res',res);
                loading.value=false
                if(res.code==1){
                    const {token,permissions,userInfo}=res.data;
                    localStorage.token=token
                    localStorage.permissions=JSON.stringify(permissions)
                    localStorage.userInfo=JSON.stringify(userInfo)

                    ElMessage.success('登录成功')
                    router.push('/nav')
                }else{
                    ElMessage.error(res.msg || "登录失败")
                }
            }).catch(err=>{
                console.log("err",err);
                loading.value = false;
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}

</script>
    
<style>
.login {
    background-color: #001529;
}
</style>